import React, { useRef } from 'react'
import { message, Modal, Space, Button } from 'antd'
import PropTypes from 'prop-types'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { CaseContext } from '../../../context'
import { updateAgentRequest, deleteAgentRequest } from '../ajax/agentAjax'
import { awaitWrap, confirmAction } from '@js/tool'
import ModalForm from './ModalForm'
import { normalStatusList } from '@src/assets/js/config'
const { confirm } = Modal
// 获取默认值
function getInitialValues (caseid, type, initialValues) {
  if (!initialValues) {
    initialValues = {}
  }
  initialValues.partyIndex = initialValues.party.map(li => li.partyid)
  return {
    caseid,
    type,
    ...initialValues
  }
}

// 表单回调，提交数据
async function onFinish (data, caseid, list, callback, hide) {
  data.caseid = caseid
  delete data.partyIndex
  if (data.subject_type === '自然人') {
    data.legal = ''
  }
  const h = message.loading('提交中', 120)
  const [e, d] = await awaitWrap(updateAgentRequest(data))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const l = list ? [...list] : []
  const ids = list.map(li => li.id)
  const index = ids.indexOf(d.id)
  l.splice(index, 1, d)
  callback(l)
  hide()
}

// 获取代理人列表
function getPartyList (caseFormRef, type) {
  if (!caseFormRef) {
    return []
  }
  const c = caseFormRef.current
  if (!c) {
    return []
  }
  const m = {
    申请人: 'applicants',
    被申请人: 'respondents'
  }
  return c.getFieldValue(m[type]) || []
}

// 删除代理人回调
function deleteAgentHandle (data, status, list, callback, hide) {
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: '您确定要撤销该代理人吗？',
    onOk: async () => {
      if (normalStatusList.indexOf(status) === -1) {
        reallyDeleteAgent(data, list, callback, hide)
      } else {
        setDisable(data, list, callback, hide)
      }
    },
    onCancel () {},
    okText: '确定',
    cancelText: '取消'
  })
}

// 真实删除代理人
async function reallyDeleteAgent (data, list, callback, hide) {
  const h = message.loading('撤销中', 120)
  const [e] = await awaitWrap(deleteAgentRequest(data.id))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const ids = list.map(li => li.id)
  const index = ids.indexOf(data.id)
  const l = list ? [...list] : []
  l.splice(index, 1)
  callback(l)
  hide()
}

// 将代理人设置为无效
async function setDisable (data, list, callback, hide) {
  const h = message.loading('撤销中', 120)
  const [e, d] = await awaitWrap(updateAgentRequest({ ...data, status: 0, partyIndex: undefined }))
  h()
  if (e) {
    return message.warning(e.message)
  }
  d.partyIndex = d.party.map(li => li.partyid)
  const ids = list.map(li => li.id)
  const index = ids.indexOf(data.id)
  const l = list ? [...list] : []
  l.splice(index, 1, d)
  callback(l)
  hide()
}

async function recoveryHandle (data, list, callback, hide) {
  const h = message.loading('恢复中', 120)
  const [e, d] = await awaitWrap(updateAgentRequest({ ...data, status: 1, partyIndex: undefined }))
  h()
  if (e) {
    return message.warning(e.message)
  }
  d.partyIndex = d.party.map(li => li.partyid)
  const ids = list.map(li => li.id)
  const index = ids.indexOf(data.id)
  const l = list ? [...list] : []
  l.splice(index, 1, d)
  callback(l)
  hide()
}

// 渲染模态框按钮
function Footer ({ formRef, hide, initialValues, value, onChange }) {
  return (
    <CaseContext.Consumer>
      {({ status }) => {
        if (initialValues.status === 0) {
          return (
            <Space>
              <Button onClick={hide}>取消</Button>
              <Button type='primary' ghost onClick={() => { confirmAction(`您确定要将 ${initialValues.name} 重新加入案件吗？`, () => { recoveryHandle(initialValues, value, onChange, hide) }) }}>恢复</Button>
            </Space>
          )
        }
        return (
          <Space>
            <Button ghost danger onClick={() => deleteAgentHandle(initialValues, status, value, onChange, hide)}>撤销</Button>
            <Button onClick={hide}>取消</Button>
            <Button type='primary' onClick={() => formRef.current.submit()}>确定</Button>
          </Space>
        )
      }}
    </CaseContext.Consumer>
  )
}

Footer.propTypes = {
  formRef: PropTypes.object,
  hide: PropTypes.func,
  initialValues: PropTypes.object,
  value: PropTypes.array,
  onChange: PropTypes.func
}

Footer.defaultProps = {
  formRef: null,
  hide: () => {},
  initialValues: {},
  value: [],
  onChange: () => {}
}

function Main ({ visible, type, hide, value, onChange, caseFormRef, initialValues }) {
  const formRef = useRef(null)
  const partyList = getPartyList(caseFormRef, type)
  return (
    <Modal
      width='700px'
      title={`修改${type}代理人`}
      open={visible}
      onCancel={hide}
      maskClosable={false}
      footer={<Footer formRef={formRef} hide={hide} initialValues={initialValues} type={type} caseFormRef={caseFormRef} value={value} onChange={onChange} />}
      destroyOnClose
    >
      <CaseContext.Consumer>
        {({ id, dictionaries, isPre }) => (
          <ModalForm ref={formRef} isPre={isPre} type={type} caseFormRef={caseFormRef} partyList={partyList} initialValues={getInitialValues(id, type, initialValues)} dictionaries={dictionaries} onFinish={d => onFinish(d, id, value, onChange, hide)} />
        )}
      </CaseContext.Consumer>
    </Modal>
  )
}

Main.propTypes = {
  visible: PropTypes.bool,
  type: PropTypes.string,
  hide: PropTypes.func,
  value: PropTypes.array,
  onChange: PropTypes.func,
  caseFormRef: PropTypes.object,
  initialValues: PropTypes.object
}

Main.defaultProps = {
  visible: false,
  type: '',
  hide: () => {},
  value: [],
  onChange: () => {},
  caseFormRef: null,
  initialValues: null
}

export default Main
